<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6" v-for="stat in stats" :key="stat.title">
        <div class="stat-card">
          <div class="stat-icon" :style="{ backgroundColor: stat.color }">
            <el-icon size="24"><component :is="stat.icon" /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stat.value }}</div>
            <div class="stat-title">{{ stat.title }}</div>
            <div class="stat-change" :class="stat.changeType">
              <el-icon><component :is="stat.changeIcon" /></el-icon>
              {{ stat.change }}
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <div class="chart-card">
          <div class="chart-header">
            <h3>销售趋势</h3>
            <el-radio-group v-model="salesPeriod" size="small">
              <el-radio-button value="week">近7天</el-radio-button>
              <el-radio-button value="month">近30天</el-radio-button>
            </el-radio-group>
          </div>
          <div class="chart-container">
            <v-chart :option="salesChartOption" style="height: 300px;" />
          </div>
        </div>
      </el-col>
      
      <el-col :span="12">
        <div class="chart-card">
          <div class="chart-header">
            <h3>订单状态分布</h3>
          </div>
          <div class="chart-container">
            <v-chart :option="orderChartOption" style="height: 300px;" />
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 最新订单 -->
    <div class="recent-orders">
      <div class="section-header">
        <h3>最新订单</h3>
        <el-button type="primary" @click="$router.push('/orders')">查看全部</el-button>
      </div>
      
      <el-table :data="recentOrders" style="width: 100%">
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="customerName" label="客户" width="120" />
        <el-table-column prop="items" label="商品" />
        <el-table-column prop="amount" label="金额" width="100">
          <template #default="{ row }">
            <span class="amount">¥{{ row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="160" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleOrder(row)">
              处理
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { ElMessage } from 'element-plus'
import { orderAPI, storeAPI } from '@/api'
import axios from 'axios'

use([
  CanvasRenderer,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const salesPeriod = ref('week')
const loading = ref(true)

// 统计数据
const stats = ref([
  {
    title: '今日订单',
    value: '0',
    change: '0%',
    changeType: 'increase',
    changeIcon: 'ArrowUp',
    icon: 'List',
    color: '#409eff'
  },
  {
    title: '今日销售额',
    value: '¥0',
    change: '0%',
    changeType: 'increase',
    changeIcon: 'ArrowUp',
    icon: 'Money',
    color: '#67c23a'
  },
  {
    title: '待处理订单',
    value: '0',
    change: '0%',
    changeType: 'increase',
    changeIcon: 'ArrowUp',
    icon: 'Warning',
    color: '#e6a23c'
  },
  {
    title: '客户评分',
    value: '0',
    change: '0',
    changeType: 'increase',
    changeIcon: 'ArrowUp',
    icon: 'Star',
    color: '#f56c6c'
  }
])

// 销售趋势数据
const salesData = ref({
  week: [],
  month: []
})

// 销售趋势图表配置
const salesChartOption = computed(() => ({
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: salesPeriod.value === 'week' 
      ? ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      : Array.from({length: 30}, (_, i) => `${i + 1}日`)
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '销售额',
      type: 'line',
      smooth: true,
      data: salesPeriod.value === 'week'
        ? salesData.value.week
        : salesData.value.month
    }
  ]
}))

// 订单状态分布数据
const orderStatusData = ref([])

// 订单状态分布图表配置
const orderChartOption = computed(() => ({
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '订单状态',
      type: 'pie',
      radius: '50%',
      data: orderStatusData.value
    }
  ]
}))

// 最新订单数据
const recentOrders = ref([])

const getStatusType = (status) => {
  const statusMap = {
    '待确认': 'warning',
    '制作中': 'primary',
    '配送中': 'info',
    '已完成': 'success',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}

const handleOrder = (order) => {
  ElMessage.success(`处理订单：${order.orderNo}`)
}

// 获取统计数据
const fetchDashboardStats = async () => {
  try {
    // 获取店铺统计数据
    const storeId = localStorage.getItem('storeId') || '1'
    const response = await axios.get(`http://localhost:8080/api/orders/stats/store/${storeId}`)
    
    if (response.data && response.data.success) {
      const data = response.data.data
      
      // 更新统计卡片数据
      stats.value[0].value = data.todayOrders || '0'
      stats.value[1].value = `¥${data.todayAmount || '0'}`
      stats.value[2].value = data.processing || '0'
      stats.value[3].value = '4.8' // 暂时使用固定值，后续可接入评价系统
      
      // 更新订单状态分布数据
      orderStatusData.value = [
        { value: data.completed || 0, name: '已完成' },
        { value: data.processing || 0, name: '进行中' },
        { value: data.paid || 0, name: '待确认' },
        { value: data.cancelled || 0, name: '已取消' }
      ]
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取最新订单
const fetchRecentOrders = async () => {
  try {
    const response = await orderAPI.getOrders()
    
    if (response && response.success) {
      // 取最新的5条订单
      recentOrders.value = response.data.slice(0, 5).map(order => ({
        orderNo: order.orderNumber,
        customerName: order.customerName || '匿名用户',
        items: order.items ? order.items.map(item => item.productName).join('、') : '暂无商品信息',
        amount: order.totalAmount,
        status: getOrderStatusText(order.status),
        createTime: order.createdAt
      }))
    }
  } catch (error) {
    console.error('获取最新订单失败:', error)
    ElMessage.error('获取最新订单失败')
  }
}

// 获取销售趋势数据
const fetchSalesTrend = async () => {
  try {
    // 模拟销售趋势数据，实际项目中应该调用相应的API
    salesData.value.week = [1200, 1800, 1500, 2200, 1900, 2800, 2400]
    salesData.value.month = Array.from({length: 30}, () => Math.floor(Math.random() * 3000) + 1000)
  } catch (error) {
    console.error('获取销售趋势失败:', error)
  }
}

// 订单状态文本映射
const getOrderStatusText = (status) => {
  const statusMap = {
    'PENDING_PAYMENT': '待支付',
    'PAID': '待确认',
    'PROCESSING': '制作中',
    'DELIVERING': '配送中',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return statusMap[status] || status
}

// 加载所有数据
const loadDashboardData = async () => {
  loading.value = true
  try {
    await Promise.all([
      fetchDashboardStats(),
      fetchRecentOrders(),
      fetchSalesTrend()
    ])
  } catch (error) {
    console.error('加载仪表板数据失败:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadDashboardData()
})
</script>

<style lang="scss" scoped>
.dashboard {
  .stats-row {
    margin-bottom: 20px;
  }
  
  .stat-card {
    background: white;
    border-radius: 8px;
    padding: 20px;
    display: flex;
    align-items: center;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      margin-right: 16px;
    }
    
    .stat-content {
      flex: 1;
      
      .stat-value {
        font-size: 24px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 4px;
      }
      
      .stat-title {
        font-size: 14px;
        color: #909399;
        margin-bottom: 8px;
      }
      
      .stat-change {
        font-size: 12px;
        display: flex;
        align-items: center;
        gap: 4px;
        
        &.increase {
          color: #67c23a;
        }
        
        &.decrease {
          color: #f56c6c;
        }
      }
    }
  }
  
  .charts-row {
    margin-bottom: 20px;
  }
  
  .chart-card {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      h3 {
        margin: 0;
        color: #303133;
        font-size: 16px;
      }
    }
  }
  
  .recent-orders {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      h3 {
        margin: 0;
        color: #303133;
        font-size: 16px;
      }
    }
    
    .amount {
      font-weight: 600;
      color: #f56c6c;
    }
  }
}
</style>